//
//  Scanner.m
//  KLGenerateSpamCode
//
//  Created by Rowling on 2023/4/26.
//  Copyright © 2023 GAEA. All rights reserved.
//

#import "Scanner.h"

@implementation Scanner
+(ScanSegment*)onScan:(NSString *)fileContent withRange:(NSRange)beginRange {
    NSRange scanRange = NSMakeRange(beginRange.location, 1);
    Stack * stack = [Stack new];
    // 转义标识
    BOOL escapeFlag = NO;
    // 标记该段属于字符串插值  123
    BOOL strJoinFlag = NO;
    unichar ch = [fileContent characterAtIndex:scanRange.location + scanRange.length - 1];
    NSString * inStackStr = [NSString stringWithCharacters:&ch length:1];
    NSString * top;

    if (![inStackStr isEqualToString:@"\""]) {
        return nil;
    }
    [stack push:inStackStr];
    while (![stack isEmpty]) {
        scanRange.length = scanRange.length + 1;
        ch = [fileContent characterAtIndex:scanRange.location + scanRange.length - 1];
        inStackStr = [NSString stringWithCharacters:&ch length:1];
        top = [stack getTop];
        if ([inStackStr isEqualToString:@"("] && top) {
            // (不是开头，栈内有数据，
            if ([top isEqualToString:@"("] || escapeFlag) {
                [stack push:inStackStr];
                // 标记该段属于字符串插值
                strJoinFlag = YES;
            }
        }
        if ([inStackStr isEqualToString:@")"] && top && [top isEqualToString:@"("]) {
            // (不是开头，栈内有数据，
            [stack pop];
        }
        if ([inStackStr isEqualToString:@"\""]) {
            // 匹配到关键词
            if (!escapeFlag) {
                if (top && [top isEqualToString:inStackStr]) {
                    [stack pop];
                } else {
                    [stack push:inStackStr];
                }
            }
        }
        if (!escapeFlag && [inStackStr isEqualToString:@"\\"]) {
            escapeFlag = YES;
        } else {
            // 转义符号 且 无标识
            escapeFlag = NO;
        }
    }
    ScanSegment * seg = [ScanSegment new];
    seg.range = scanRange;
    seg.strJoinFlag = strJoinFlag;
    return  seg;
}
@end
